/* eslint-disable no-unused-vars */
/* eslint-disable no-shadow */
import React, { memo, useEffect, useCallback, useState } from "react";
import { View, Text, Image } from "@tarojs/components";
import { Cell, CellGroup, Icon } from "@antmjs/vantui";
import Taro, { useDidShow } from "@tarojs/taro";
import { useSelector, useDispatch, shallowEqual } from "react-redux";
import { updateState } from "@/store/actions/global";
import debounce from "lodash/debounce";
import axios from "@/axios";
import { getQiniuToken } from "@/axios/api/qiniu";
import { getUserData, updateUserInfo } from "@/axios/api/user";
import { getUserInfo, chooseImage, uploadQiniu } from "@/utils/utils";
import { themeColor, imgUrl } from "@/utils/config";
import "./index.less";

const Index = () => {
  const { globalData } = useSelector(
    (state) => ({ globalData: state.globalData }),
    shallowEqual
  );
  const dispatch = useDispatch();
  const { isLogin, userInfo, qiniuToken } = globalData;
  const [show, setShow] = useState(0);
  const { username = "", avatar = "", fans = 0, follow = 0 } = userInfo || {};
  const handleLogin = useCallback(
    debounce(
      async () => {
        console.log("login");
        const data = await getUserInfo();
        if (data) {
          const { userInfo } = data;
          const payload = {
            userInfo,
            isLogin: true,
          };
          dispatch(updateState(payload));
        }
      },
      500,
      {
        leading: true,
        trailing: false,
      }
    ),
    [isLogin]
  );

  const handleClickNav = useCallback(
    debounce(
      (type) => {
        console.log("CLICK", type);
        let url = "";
        switch (type) {
          case 1:
            url = "/pages/basket/index";
            break;
          case 2:
            url = "/pages/userCenter/index"
            break;
          case 3:
            url = "/pages/userCenter/index?type=1"
            break;
          case 4:
            url = "/pages/recipeAdd/index";
            break;
          case 5:
            url = "/pages/history/index";
            break;
          case 7:
            url = "/pages/relationShip/index";
            break;
          case 8:
            url = "/pages/relationShip/index?type=" + 1;
            break;
          case 6:
            Taro.showModal({
              title: "关于",
              content: `杭州师范大学2022届软件工程182班本科毕业设计
            \r\n作者:Lancelot
            \r\n联系邮箱:812949176@qq.com
            \r\n后端服务支持:晓梦`,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                }
              },
            });
            return;
            break;
        }
        if (!isLogin) {
          dispatch(
            updateState({
              isShowGrant: true,
            })
          );
        } else {
          jumpTo(url);
        }
      },
      500,
      {
        leading: true,
        trailing: false,
      }
    ),
    [isLogin]
  );
  const jumpTo = (url) => {
    Taro.navigateTo({
      url,
    });
  };

  const handleAavatar = async () => {
    try {
      const arr = await chooseImage(1);
      let url = await uploadQiniu(arr, qiniuToken, "avatar/");
      let payload = {
        ...userInfo,
        avatar: url,
      };
      updateUserData(payload);
    } catch (err) {
      getQiniuConfig();
      Taro.showModal({
        title: "提示",
        content: `图片上传错误,请重新上传`,
        showCancel: false,
      });
      return;
    }
  };
  const updateUserData = (userInfo) => {
    axios
      .post(updateUserInfo, {
        userInfo,
      })
      .then((res) => {
        if (res.code === 200) {
          getData();
        }
      });
  };
  const getData = () => {
    axios.post(getUserData).then((res) => {
      const { data, code } = res;
      if (code === 200) {
        const { userInfo, showPublish } = data;
        setShow(showPublish);
        Taro.setStorageSync("userInfo", userInfo);
        dispatch(updateState({ userInfo }));
      }
    });
  };
  const getQiniuConfig = () => {
    axios.post(getQiniuToken).then((res) => {
      const { data, code } = res;
      if (code === 200) {
        dispatch(updateState({ qiniuToken: data.uploadToken }));
      }
    });
  };
  useEffect(() => {
    if (!isLogin) {
      return;
    }
    getData();
  }, [isLogin, dispatch]);
  useDidShow(() => {
    getQiniuConfig();
  })
  return (
    <View className='mine'>
      {!isLogin ? (
        <View className='no-login'>
          <View className='app-logo'>
            <Image src={imgUrl + "logo.png"} mode='widthFix' />
            <View className='text'>
              <Text>就离谱鹅</Text>
            </View>
          </View>
          <View className='m-bottom'>
            <View className='btn-login' onClick={handleLogin}>
              微信授权登录
            </View>
          </View>
        </View>
      ) : (
          <View className='user'>
            <View className='poster'>
              <View className='info'>
                <View className='left' onClick={handleAavatar}>
                  <Image src={avatar}></Image>
                </View>
                <View className='right'>
                  <View className='username'>
                    <Text>{username}</Text>
                  </View>
                  <View className='follow-fans'>
                    <View className='follow' onClick={() => handleClickNav(7)}>
                      <Text className='num'>{follow}</Text>关注
                  </View>
                    <View className='fans' onClick={() => handleClickNav(8)}>
                      <Text className='num'>{fans}</Text>粉丝
                  </View>
                  </View>
                </View>
              </View>
            </View>
            {show? <View className='card-group'>
              <View className='card' onClick={() => handleClickNav(1)}>
                <Icon name='bag' size='60' color={themeColor}></Icon>
                <View className='label'>菜篮子</View>
              </View>
              <View className='card' onClick={() => handleClickNav(2)}>
                <Icon name='description' size='60'></Icon>
                <View className='label'>我的菜谱</View>
              </View>
              <View className='card' onClick={() => handleClickNav(3)}>
                <Icon name='star' size='60' color='#ffd21e'></Icon>
                <View className='label'>我的收藏</View>
              </View>
            </View>
            :null}
           
            <View className='nav'>
              <CellGroup inset>
                {show? <Cell
                  title='发布菜谱'
                  isLink
                  icon='records'
                  onClick={() => handleClickNav(4)}
                />:null}
                <Cell
                  title='历史浏览'
                  isLink
                  icon='clock-o'
                  onClick={() => handleClickNav(5)}
                />
                <Cell
                  title='关于'
                  isLink
                  icon='question-o'
                  onClick={() => handleClickNav(6)}
                />
              </CellGroup>
            </View>
          </View>
        )}
    </View>
  );
};

export default memo(Index);
